import React, { useState, useEffect } from 'react'
import { useNavigate,useSearchParams } from 'react-router-dom';
import './Css/addcos.css'

import type { FormProps } from 'antd';
import { Button, Checkbox, Form, Input, Col, Row, Divider } from 'antd';
import type { GetProp } from 'antd';
import type { CheckboxProps } from 'antd';


import { getPermission,cosupdate,coseditcos } from '../../../request/api'




export default function Addcos() {
    const navigate = useNavigate()
    const [searchParams] = useSearchParams();
    const id = searchParams.get('_id')

    useEffect(() => {
        getpermission()
        
    }, [])


    // 获取权限数据
    let [data, setdata] = useState([])
    const getpermission = async () => {
        let res = await getPermission({})
        setdata(res.info_list[0].children)
        Coseditcos()
    }

    // 数据回显
    let [identity_name, setidentity_name] = useState('')
    let [identity_describe, setidentity_describe] = useState('')
    let [Permissions, setPermissions] = useState([])
    const Coseditcos = async () => {
        let res = await coseditcos({ _id: id })
        console.log(res);
        setidentity_name(res.data[0].identity_name)
        setidentity_describe(res.data[0].identity_describe)
        setPermissions(res.data[0].Permissions)
    }

    const updatacos = async () => {
        let from = {
            _id:id,
            identity_name,
            identity_describe,
            Permissions,
            static_time: new Date().toLocaleString()
        }
        let res = await  cosupdate({ from })
        if (res.code == 200) {
            alert('修改成功')
            navigate('/home/System/cos_management')
            setidentity_name('')
            setidentity_describe('')
            setPermissions([])
        }

    }



    const onChange: GetProp<typeof Checkbox.Group, 'onChange'> = (checkedValues) => {
        setPermissions(checkedValues)
    };

    type FieldType = {
        username?: string;
        password?: string;
        remember?: string;
    };

    const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
        console.log('Success:', values);
    };

    const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };








    return (
        <div style={{ width: '100%' }}>
            <div className='title'>
                修改角色
            </div>
            <div className='addcos'>
                <Form
                    name="basic"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item<FieldType>
                        label="角色名称"
                        rules={[{ required: true, message: '请输入角色名称' }]}
                    >
                        <Input value={identity_name} onChange={(e) =>   setidentity_name(e.target.value)} />
                    </Form.Item>

                    <Form.Item<FieldType>
                        label="角色介绍"
                        rules={[{ required: true, message: '请输入角色介绍' }]}
                    >
                        <Input value={identity_describe} onChange={(e) => setidentity_describe(e.target.value)} />
                    </Form.Item>
                    <Form.Item<FieldType> label="角色权限">
                        <Checkbox.Group onChange={onChange} >
                            {
                                data.map((item: any) => {
                                    return (
                                        <div key={item._id} style={{ marginBottom: '1rem' }}>
                                            <Checkbox value={item._id} style={{ fontSize: '16px' }} >{item.Permissions_name}</Checkbox>
                                            <Row >
                                                {
                                                    item.children.map(ele => {
                                                        return <Col span={8}>
                                                            <Checkbox value={ele._id} style={{ width: '5rem' }} checked={ele._id in Permissions?true:false} >{ele.Permissions_name}</Checkbox>
                                                        </Col>
                                                    })
                                                }
                                            </Row>
                                        </div>

                                    )
                                })
                            }
                        </Checkbox.Group>
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" htmlType="submit" style={{ marginRight: '1rem' }} onClick={() => {
                            updatacos()
                        }}>
                            修改
                        </Button>
                        <Button type="primary" htmlType="submit" onClick={()=>{
                            navigate('/home/system/cos_management')
                        }}>
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}
